package com.edou.system.controller.front;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.base.controller.BaseController;
import com.edou.system.entity.SysRegion;
import com.edou.system.form.SysRegionForm;
import com.edou.system.service.ISysRegionService;

/**
 * 地区下拉选择controller
 * @creator     admin
 * @create-time 2017年9月30日   下午12:13:52
 * @email admin@edou.com
 * @company www.edou.com
 * @version 1.0
 */
@Controller("sysRegionSelectController")
@Scope("prototype")
@RequestMapping(value = "/system/region")
public class SysRegionSelectController extends BaseController{
	
	@Resource(name = "sysRegionServiceImpl")
	private ISysRegionService sysRegionService;
	
	/**
	 * 根据上级ID查询区域
	 * @param model
	 * @param request
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/listSysRegionByParentId.htm", method = RequestMethod.POST)
	public ModelAndView listSysRegionByParentId(@ModelAttribute SysRegionForm model,HttpServletRequest request,HttpSession session){
		try {
			//查询区域集合
			List<SysRegion> itemList = null;
			if(null == model.getCondition().getParentId()) {
				//查询所有省份
				itemList = sysRegionService.listProvinceAll();
			}else {
				itemList = sysRegionService.listSysregionByCondition(model.getCondition());
			}
			//组装区域数据
			JSONArray root = new JSONArray();
			for(SysRegion item : itemList) {
				JSONObject json = new JSONObject();
				json.put("id", item.getId());
				json.put("name", item.getName());
				
				root.add(json);
			}
			
			return ajaxJSON(Status.success,"查询成功",root);
		} catch (Exception e) {
			String msg = "根据上级ID查询区域数据时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "查询失败，请稍后重试");
		}
	}
}
